<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.channelName"
        placeholder="渠道名称"
        style="width: 200px;"
        clearable
      />
      <el-select
        v-model="listQuery.orgId"
        placeholder="所属校区"
        clearable
        style="width: 180px"
        class="filter-item1"
        @change="handleOrgIdChange"
      >
        <el-option
          v-for="option in orgList"
          :key="option.key"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.channelTypeId"
        placeholder="渠道类型"
        clearable
        style="width: 180px"
        class="filter-item1"

      >
        <el-option
          v-for="option in channelTypeIdOptions"
          :key="option.key"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >{{ $t("table.search") }}</el-button
      >
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >{{ $t("table.add") }}</el-button
      >
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="渠道名称" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.channelName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属渠道类型" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.channelTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属校区" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.organizationName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.createTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"
          >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="rules"
        label-width="140px"
        class="userForm"
        style="width: 420px; margin-left:0px;"
      >
        <el-form-item label="渠道名称" prop="channelName">
          <el-input
            v-model="userForm.channelName"
            placeholder="请输入渠道名称"
            maxlength="32"
          />
        </el-form-item>
        <el-form-item label="所属校区" prop="organizationId">
          <el-select
            v-model="userForm.organizationId"
            class="filter-item"
            placeholder="请选择所属校区"
            style="width: 100%;"
            @change="handleFormOrgIdChange"
          >
            <el-option
              v-for="item in orgList"
              :key="item.key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="渠道类型" prop="channelTypeId">
          <el-select
            v-model="userForm.channelTypeId"
            placeholder="请选择渠道类型"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="option in formChannelTypeIdOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("table.cancel")
          }}</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          :loading="submitLoading"
          type="primary"
          @click="createData"
        >{{ $t("table.confirm") }}</el-button
        >
        <el-button v-else :loading="submitLoading"  type="primary" @click="updateData">{{
          $t("table.confirm")
          }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchChannelList,
    createChannel,
    deleteChannel,
    updateChannel
  } from "@/api/business/channel";

  import { fetchOrg, fetchChannel } from "@/api/clue";

  import waves from "@/directive/waves"; // 水波纹指令
  import { parseTime } from "@/utils";

  import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

  export default {
    name: "UserTable",
    components: { Pagination },
    directives: {
      waves
    },
    filters: {},
    data() {
      return {
        tableKey: 0,
        orgList: null,
        channelTypeIdOptions: [], //渠道类型
        formChannelTypeIdOptions: [],

        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          current: 1,
          size: 20,
          channelName: null,
          channelTypeId: null,
          orgId: ""
        },
        dialogFormVisible: false,
        dialogStatus: "",
        textMap: {
          update: "编辑",
          create: "添加"
        },
        userForm: {
          channelId: "",
          channelName: "",
          organizationId: '',
          channelTypeId: ""
        },
        rules: {
          channelName: [
            { required: true, message: "请输入渠道名称", trigger: "blur" },
            { max: 16, message: "请不要超过 16 个字符", trigger: "blur" }
          ],
          organizationId: [
            { required: true, message: "请选择所属校区", trigger: "change" }
          ],
          channelTypeId: [
            { required: true, message: "请选择渠道类型", trigger: "change" }
          ]
        },
        submitLoading: false
      };
    },
    created() {
      this.getList();
      this.getOrgList();
    },
    methods: {
      getList() {
        this.listLoading = true;
        fetchChannelList(this.listQuery).then(response => {
          this.list = response.data;
          this.total = response.count;
          this.listLoading = false;
        });
      },
      getOrgList() {
        this.listLoading = true;
        const queryMethod = "queryChannelType"
        const queryKey = '0'
        fetchOrg(queryMethod,queryKey).then(response => {
          this.orgList = response.data;
          this.listLoading = false;
        });
      },
      handleOrgIdChange(orgId) {
        this.listQuery.channelTypeId = "";
        this.getchannelTypeIdOptions(orgId);
      },
      //渠道类型（校区Id）
      getchannelTypeIdOptions(queryId, queryKey) {
        fetchChannel(queryId, "2").then(response => {
          this.channelTypeIdOptions = response.data;
        });
      },
      handleFormOrgIdChange(orgId) {
        this.userForm.channelTypeId = "";
        this.getFormchannelTypeIdOptions(orgId);
      },
      //渠道类型（校区Id）
      getFormchannelTypeIdOptions(queryId, queryKey) {
        fetchChannel(queryId, "2").then(response => {
          this.formChannelTypeIdOptions = response.data;
        });
      },

      handleFilter() {
        this.listQuery.current = 1;
        this.getList();
      },
      resetUserForm() {
        this.userForm = {
          channelId: "",
          channelName: "",
          organizationId:'',
          channelTypeId : ""
        };
        this.formChannelTypeIdOptions = [];
      },
      handleCreate() {
        this.resetUserForm();
        this.dialogStatus = "create";
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs["userForm"].clearValidate();
        });
      },
      createData() {
        this.$refs["userForm"].validate(valid => {

          if (valid) {
            this.submitLoading = true
            createChannel(this.userForm).then(() => {
              this.dialogFormVisible = false
              this.submitLoading = false
              this.getList()
              this.$message({
                message: "创建成功",
                type: "success"
              });
            }).catch(err => {
              this.submitLoading = false
            })
          }
        });
      },
      handleUpdate(row) {
        this.userForm = Object.assign({}, row); // copy obj
        this.handleFormOrgIdChange(this.userForm.organizationId);
        this.userForm.channelTypeId = row.channelTypeId
        this.dialogStatus = "update";
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs["userForm"].clearValidate();
        });
      },
      updateData() {
        this.$refs["userForm"].validate(valid => {
          if (valid) {
            this.submitLoading = true
            updateChannel(this.userForm).then(() => {
              this.dialogFormVisible = false
              this.submitLoading = false
              this.$message({
                message: "更新成功",
                type: "success"
              })
              this.getList()
            }).catch(err => {
              this.submitLoading = false
            })
          }
        });
      },
      handleDelete(row) {
        this.$confirm(
          "此操作将永久删除该数据：" + row.channelName + ", 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            this.listLoading = true;
            deleteChannel(row.channelId).then(() => {
              this.listLoading = false;
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              const index = this.list.indexOf(row);
              this.list.splice(index, 1);
            }).catch(err => {
              this.listLoading = false
            })
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v =>
          filterVal.map(j => {
            if (j === "createTime") {
              return parseTime(v[j]);
            } else if (j === "userSex") {
              return this.$options.filters["sexNameFilter"](v[j]);
            } else if (j === "userStatus") {
              return this.$options.filters["statusNameFilter"](v[j]);
            } else {
              return v[j];
            }
          })
        );
      }
    }
  };
</script>
